const modules = import.meta.glob('../pages/**/*.jsx')
import LazyLoad from '../router/lazyLoad'

// 处理路由
const formatRoutes = data => {
  return data.map(item => {
    const element = modules[`../pages${item.path}/index.jsx`] ?
      LazyLoad(modules[`../pages${item.path}/index.jsx`]) : null

    const pathArr = item.path.split('/')
    const path = pathArr.slice(item.level).join('/')

    return {
      route_path: item.path,
      path,
      element,
      icon: item.icon,
      level: item.level,
      menu_id: item.menu_id,
      parent_id: item.parent_id,
      label: item.name,
      key: item.code
    }
  })
}

// 将路由菜单数据格式化成树形结构
const formatToTree = data => {
  const parents = data.filter(item => item.parent_id === null)
  const children = data.filter(item => item.parent_id !== null)

  const childrenMap = new Map()
  children.forEach(child => {
    if (!childrenMap.has(child.parent_id)) {
      childrenMap.set(child.parent_id, [])
    }
    childrenMap.get(child.parent_id).push(child)
  })

  const dataToTree = parents.map(parent => {
    return {
      ...parent,
      children: childrenMap.get(parent.menu_id) || []
    }
  })

  return dataToTree
}

// 将后端返回的菜单数据格式化成树形
export const getMenuTree = data => {
  return formatToTree(formatRoutes(data))
}

// 获取第一个有效菜单地址
export const getFirstValidMenuAddress = data => {
  const menus = formatToTree(formatRoutes(data))

  const findMenuAddress = (menus) => {
    for (const menu of menus) {
      if (menu.route_path) {
        return menu.route_path // 返回第一个有效的菜单地址
      }
      if (menu.children) {
        const childAddress = findMenuAddress(menu.children)
        if (childAddress) {
          return childAddress // 从子菜单中返回有效地址
        }
      }
    }
    return null // 如果没有找到有效地址，返回 null
  }

  return findMenuAddress(menus)
}